package com.wlq.demo.uitls;

import com.wlq.demo.anno.ForUpdate;

import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.*;

/**
 * @author csb
 * @description: TODO
 * @date 2023/4/14 9:50
 */
public class undifineUtil {

    /**
     * 获取变更内容
     * @param oldBean 更改前的Bean
     * @param newBean 更改后的Bean
     * @param <T>
     * @return
     */
    public static <T> String getChangedFields(T oldBean, T newBean){
        Field[] fields = newBean.getClass().getDeclaredFields();
        StringBuilder builder = new StringBuilder();
        for(Field field : fields) {
            field.setAccessible(true);
            //skip filed without @ForUpdate
            if (!field.isAnnotationPresent(ForUpdate.class)) {
                continue;
            }

            try {
                Object oldValue = field.get(oldBean);
                Object newValue = field.get(newBean);
                if(!Objects.equals(newValue, oldValue)) {
                    builder.append("修改【");
                    builder.append(field.getAnnotation(ForUpdate.class).fieldName()); //获取字段名称
                    builder.append("】，'");
                    builder.append(oldValue);
                    builder.append("'为'");
                    builder.append(newValue);
                    builder.append("'\n");
                }
            } catch (Exception e) {
                System.out.println(e);
            }
        }

        return builder.toString();
    }

}
